﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P0911Controller : ControllerBase
    {
        [HttpPost]
        public ActionResult<MQResponse> CreateJE(dynamic objparam)
        {


//            {
//                "username" :"itais",
//  "password" : "prc_IT_ais",
//  "orderid" : "881fb89d-3a55-4ddc-88db-9278e1abe5be"
//} 
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;


            Log4Net.Debug(objparam);
            //用了新的方式，哈哈方便多了
            P0911param param = Common.JsonHelper.JsonToObject<P0911param>((objparam).ToString());

            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增JE单据 {param.orderid}");

                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    formName = "P0911_W0911I",
                    version = "MBR001",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    formActions = new FormActionsCollection
                    (
                        new FSREvent[]
                        {
                            new FSREvent() { controlID="83", command="DoAction"  }
                        }
                    )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P0911_W0911I",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;

                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P0911_W0911A"))
                {

                    List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                    FormActionsCollection fs = new FormActionsCollection();
                    DataRow lastrow = new DataTable().NewRow();
                    foreach (DataRow dr in new BLL.orderHandler().GetJEOrder(param.orderid)[0].Rows)
                    {
                        gridcolumnCollection col = new gridcolumnCollection();
                        col.Add(new gridcolumnevent() { columnID = "12", value = dr["GLANI"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "13", value = dr["amount"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "16", value = dr["GLSBLT"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "15", value = dr["GLSBL"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "14", value = dr["detailremark"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "597", value = dr["GLcknu"].ToString(), command = "SetGridCellValue" });


                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                        lastrow = dr;
                    }
                    //fs.AddRange(
                    //     new FormActionsCollection
                    //              (
                    //                  new FSREvent[]
                    //                  {
                    //                    //new FSREvent() { controlID="11", command="SetControlValue", value= lastrow["BU"].ToString() },
                    //                    //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                    //                    new FSREvent() { controlID="320", command="SetControlValue",value=lastrow["sys_type"].ToString()   },
                    //                    new FSREvent() { controlID="48", command="SetControlValue",value= lastrow["sys_code"].ToString() },
                    //                    new FSREvent() { controlID="57", command="SetControlValue",value= lastrow["sys_remark"].ToString() },
                    //                   }
                    //              )
                    //    );
                    GridAction _gridAction = new GridAction();
                    _gridAction.gridID = "1";
                    _gridAction.gridRowInsertEvents = gridrows;

                    //fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                    //fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                    ActionRequest actionRequest = new ActionRequest()
                    {
                        formOID = "W0911A",
                        formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {
                                              
                                            new FSREvent() { controlID="320", command="SetControlValue",value=lastrow["sys_type"].ToString()   },
                                            new FSREvent() { controlID="48", command="SetControlValue",value=lastrow["paytype"].ToString().StartsWith("MCL")? lastrow["sys_code"].ToString():"" },
                                            new FSREvent() { controlID="57", command="SetControlValue",value=lastrow["sys_remark"].ToString().Length>30 ? lastrow["sys_remark"].ToString().Substring(0,30):lastrow["sys_remark"].ToString() },
                                            new FSREvent() { controlID="54", command="SetControlValue",value=SomeHandler.GetDateFormat(param.username, Convert.ToDateTime(lastrow["sys_date"].ToString())) },


                                            new FSREvent() {
                                                            controlID ="1.0",
                                                            command ="SelectRow",
                                                            gridAction =_gridAction
                                                            },

                                            new FSREvent() { controlID="2", command="DoAction"  }
                                         }
                                     )
                                 ,
                        stopOnWarning = "false"
                    };
                    asrequest = new ApplicationStackRequest()
                    {
                        outputType = "VERSION2",
                        allowCache = true,
                        action = "execute",
                        actionRequest = actionRequest,
                        stackId = response.stackId,//上一次返回的值
                        stateId = response.stateId,
                        rid = response.rid
                    };

                    response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    needclose = true;
                    stackId = response.stackId;
                    stateId = response.stateId;
                    rid = response.rid;

                    System.Threading.Thread.Sleep(20000);
                    if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P0911_W0911A"))
                    {
                        JObject obj = response.ToJObject();
                        //应该查询到数据
                        string NAno = $"{obj["fs_P0911_W0911A"]["data"]["z_ICU_258"]["value"].ToString()}#{obj["fs_P0911_W0911A"]["data"]["z_DOC_297"]["value"].ToString()}" ;
                        Console.WriteLine($"{DateTime.Now.ToString()} 生成日记账凭证单:{NAno}");
                        execresult.Result = NAno;
                    }
                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W0911A"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                }
                #endregion
            }
            return execresult;
        }


    }
}